package com.dragon.connector.imServer.serverProcesser;

import com.dragon.connector.imServer.protoBuilder.ReceiveMessageResponseBuilder;
import com.dragon.connector.imServer.session.LocalSession;
import com.dragon.connector.imServer.session.ServerSession;
import com.dragon.connector.imServer.session.service.SessionManger;
import com.dragon.protoJo.ProtoInstant;
import com.dragon.protoJo.bean.msg.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class NotifyMessageProcesser extends AbstractServerProcesser{


    /**
     * 转发通知
     * @param ctx
     * @param proto
     * @return
     */
    @Override
    public Boolean actionTcp(ChannelHandlerContext ctx, ProtoMsg.Message proto) {
        ProtoMsg.MessageNotification messageNotification = proto.getNotification();
        log.info("chatMsg | from="
                + messageNotification.getNoId()
                + " , noid =" + messageNotification.getNoId()
                + " , time =" + messageNotification.getTimestamp()
                + " , json =" + messageNotification.getJson());
        // 获取接收人的chatId
        String to = String.valueOf(messageNotification.getNoId());
        List<ServerSession> toSessions = SessionManger.inst().getSessionsBy(to);
        ProtoInstant.ResultCodeEnum resultCode = ProtoInstant.ResultCodeEnum.SUCCESS;
        if(toSessions == null){
            //接收方离线
            log.info("[" + to + "] 不在线，需要保存为离线消息，请保存到nosql如mongo中!");
            resultCode = ProtoInstant.ResultCodeEnum.NOT_ONLINE;
        } else {
            // 发送消息给接收方
            toSessions.forEach(serverSession -> {
                serverSession.writeAndFlush(proto);
            });
        }
        /**
         * 通知客户端：消息发送成功
         */
        long seqNo = proto.getSequence();
        ProtoMsg.Message response =
                ReceiveMessageResponseBuilder.buildChatResponse(resultCode,seqNo);
        ctx.writeAndFlush(response);
        return true;
    }

    @Override
    public ProtoMsg.HeadType op() {
        return ProtoMsg.HeadType.MESSAGE_NOTIFICATION;
    }

    @Override
    public Boolean action(LocalSession ch, ProtoMsg.Message proto) {
        return null;
    }
}
